package com.alibaba.citrus.cr.mn.order.center.facade.function.convert;

import com.alibaba.citrus.cr.common.enums.ordercenter.*;
import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.*;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.LogisticWarehouseQueryRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.SalesBizOrgByBuQueryRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ShipToPartyByAccurateQueryRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.*;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.*;
import com.alibaba.citrus.cr.mn.order.center.facade.function.dataobject.AtomOrderDO;
import com.alibaba.citrus.cr.mn.order.center.forecastorder.ability.NormalPriceQueryUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.epoch.app.bcorder.model.dto.WarehouseInfo;
import com.epoch.app.crb2btradecenter.domain.order.model.Order;
import com.epoch.app.crb2btradecenter.domain.orderline.model.OrderLine;
import com.epoch.app.crpricecenter.model.enums.PriceTypeEnum;
import com.epoch.app.mnordercenter.model.dto.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.alibaba.citrus.cr.common.constant.OrderFeaturesKey.*;

/**
 * @author zhangxiaorui
 * @ClassName SalesOrderParamsConvertService
 * @description: TODO
 * @date 2023/05/17 15:27
 * @version: 1.0
 */
@Service
public class SalesOrderParamsConvertService extends AbstractOrderParamsConvertService<SalesOrderAtomCreateRequest, AtomOrderDO>{
    private static final Log log = Log.getLogger(SalesOrderParamsConvertService.class);

    private static final String SALES_ORGANIZATION_CODE = "20";

    @Resource
    private BaseDataServiceAdapter baseDataServiceAdapter;
    @Resource
    private CargoZoneAdapter cargoZoneAdapter;
    @Resource
    private ShipToPartyAbilityAdapter shipToPartyAbilityAdapter;
    @Resource
    private ItemQueryAdapter itemQueryAdapter;
    @Resource
    private SalesOrgAbilityAdapter salesOrgAbilityAdapter;
    @Resource
    private NormalPriceQueryUtils normalPriceQueryUtils;

    @Override
    public List<AtomOrderDO> convert(List<SalesOrderAtomCreateRequest> requestList) {
        List<AtomOrderDO> companyOrderDOS = doConvert(requestList);

        // 300类别订单复制出F-B订单
        if (OrderCategoryEnum.STOCK.getCode().equals(requestList.get(0).getOrderCategoryCode())) {
            List<AtomOrderDO> groupOrderDOS = convertGroupOrder(companyOrderDOS, requestList);
            //F-B订单的对应关系 key=来源系统+"_"+来源订单号 value=AtomOrderDO
            Map<String, AtomOrderDO> groupOrderMap = groupOrderDOS.stream()
                    .collect(Collectors.toMap(AtomOrderDO::getUniqueKey, Function.identity(), (k1, k2) -> k2));
            //B-b订单的对应关系 key=来源系统+"_"+来源订单号 value=AtomOrderDO
            Map<String, AtomOrderDO> companyOrderMap = companyOrderDOS.stream()
                    .collect(Collectors.toMap(AtomOrderDO::getUniqueKey, Function.identity(), (k1, k2) -> k2));
            companyOrderMap.forEach((key, value) -> {
                if (groupOrderMap.containsKey(key)) {
                    value.setFactoryBusinessOrderDO(groupOrderMap.get(key));
                }
            });
        }
        return companyOrderDOS;
    }

    private List<AtomOrderDO> convertGroupOrder(List<AtomOrderDO> atomOrderDOS, List<SalesOrderAtomCreateRequest> requestList) {
        //转map key = fromSys_sourceOrderNo
        Map<String, SalesOrderAtomCreateRequest> requestMap = requestList.stream().collect(Collectors.toMap((request) -> request.getFromSys() + "_" + request.getSourceOrderNo(), Function.identity(), (k1, k2) -> k2));
        // 客户送达方
        Map<String, ShipToPartyByAccurateQueryDTO> shipToPartyMap = queryShipToPartyByAccurate(requestList);

        List<AtomOrderDO> groupOrderDOS = new ArrayList<>();
        atomOrderDOS.forEach(companyOrderDO -> {
            Order companyOrder = companyOrderDO.getOrder();

            SalesOrderAtomCreateRequest bizRequest = requestMap.get(companyOrder.getFromSys() + "_" + companyOrder.getSourceOrderNo());
            ShipToPartyByAccurateQueryDTO shipToParty = shipToPartyMap.get(bizRequest.getGroupShipToPartyCode());
            if (Objects.isNull(shipToParty)) {
                throw new FunctionException("OC-01-001-01-16-033", "集团送达方编码/名称不存在");
            }

            //复制B-b参数,生成F-B订单
            Order groupOrder = new Order();
            //复制主单
            BeanUtils.copyProperties(companyOrder, groupOrder);

            Map<String, String> featuresMap = JSONObject.parseObject(bizRequest.getFeatures(), new TypeReference<Map<String, String>>() {});
            featuresMap = Optional.ofNullable(featuresMap).orElse(Maps.newHashMap());
            //收货仓信息
            groupOrder.setReceiveFactoryCode(featuresMap.get("deliveryFactoryCode"));
            groupOrder.setReceiveStockCode(featuresMap.get("stockCode"));
            groupOrder.setReceiveWareHouseOutCode(featuresMap.get("shippingWarehouseCode"));
            groupOrder.setReceiveWareHouseName(featuresMap.get("shippingWarehouseName"));
            //是否自动创建履约单
            groupOrder.setAutoFulfillment(AutoFulfillmentEnum.FALSE.getCode());
            //履约方式
            groupOrder.setFulfillmentTypeCode(FulfillmentTypeEnum.EXTERNAL_TO_EXTERNAL.getCode());
            //客户售达方编码
            groupOrder.setCustomerCode(bizRequest.getGroupCustomerCode());
            //客户售达方名称
            groupOrder.setCustomerName(bizRequest.getGroupCustomerName());
            //客户送达方编码
            groupOrder.setReceiveAddressCode(bizRequest.getGroupShipToPartyCode());
            //客户送达方名称
            groupOrder.setReceiveDetailAddress(shipToParty.getSoldToPartyName());
            //来单时间
            if (StringUtils.isNotBlank(groupOrder.getFeatures())) {
                Map<String, String> map = JSON.parseObject(groupOrder.getFeatures(), Map.class);
                map.remove(SOURCE_ORDER_TIME);
                map.remove(KA_SYSTEM);
                map.remove(KA_AREA);
                groupOrder.setFeatures(JSON.toJSONString(map));
            }
            //客户采购订单号
            groupOrder.setCustomerReferenceNo(null);
            //客户采购订单日期
            groupOrder.setCustomerPurchaseDate(null);
            //订单类型编码数据库并没有存储，而是存储的订单类型
            groupOrder.setOrderType(SalesOrderTypeEnum.GROUP_STD_ORDER.getCode());
            groupOrder.setOrderTypeName(SalesOrderTypeEnum.GROUP_STD_ORDER.getDesc());
            //外部销售渠道编码
            groupOrder.setSaleChannelOutCode(shipToParty.getOuterSalesDepartmentCode()); // 销售办公室
            //销售渠道名称
            groupOrder.setSaleChannelName(shipToParty.getOuterSalesDepartment());
            //外部销售部门编码
            groupOrder.setDepartmentOutCode(shipToParty.getOuterSalesGroupCode()); // 销售组
            //销售部门名称
            groupOrder.setDepartmentName(shipToParty.getOuterSalesGroup());
            //外部销售组织编码
            groupOrder.setOrganizationOutCode(bizRequest.getGroupSalesOrganizationCode());
            //重置内部属性
            Map<String, String> idMap = findId(Lists.newArrayList(bizRequest.getGroupSalesOrganizationCode(), shipToParty.getOuterSalesGroupCode(), shipToParty.getOuterSalesDepartmentCode()), companyOrder.getProductGroupCode());
            //销售组织编码
            groupOrder.setOrganizationCode(idMap.get(bizRequest.getGroupSalesOrganizationCode()));
            //销售部门编码
            groupOrder.setDepartmentCode(idMap.get(shipToParty.getOuterSalesDepartmentCode()));
            //销售渠道编码
            groupOrder.setSaleChannelCode(idMap.get(shipToParty.getOuterSalesGroupCode()));
            //业务渠道编码
            groupOrder.setChannelCode(SALES_ORGANIZATION_CODE);
            //外部渠道编码
            groupOrder.setChannelOutCode(SALES_ORGANIZATION_CODE);
            //预报订单号
            groupOrder.setPreOrderNo(null);

            //查询价格信息
            SalesOrderAtomCreateRequest createRequest = new SalesOrderAtomCreateRequest();
            BeanUtils.copyProperties(bizRequest, createRequest);
            //销售组织
            createRequest.setSalesOrganizationCode(bizRequest.getGroupSalesOrganizationCode());
            //业务渠道
            createRequest.setBusinessChannel(SALES_ORGANIZATION_CODE);
            //送达方
            createRequest.setCustomerCode(bizRequest.getGroupCustomerCode());
            //售达方
            createRequest.setShipToPartyCode(bizRequest.getGroupShipToPartyCode());
            //销售部门
            createRequest.setSalesDepartmentCode(shipToParty.getOuterSalesDepartmentCode());
            Map<String, PolicyPriceQueryRequest> priceQueryRequestMap = queryGoodsDetailPrice(createRequest);

            //复制明细
            List<OrderLine> groupOrderLines = Lists.newArrayList();
            companyOrderDO.getOrderLines().forEach(line -> {
                OrderLine groupOrderLine = new OrderLine();
                BeanUtils.copyProperties(line, groupOrderLine);
                setPrice(groupOrderLine, priceQueryRequestMap);
                //F-B与B-b明细差异参数设置
                String features = groupOrderLine.getFeatures();
                if (StringUtils.isNotBlank(features)) {
                    Map<String, String> map = JSON.parseObject(features, Map.class);
                    //来单单位
                    if (map.containsKey(SOURCE_UNIT)) {
                        map.remove(SOURCE_UNIT);
                    }
                    //来单价格
                    if (map.containsKey(SOURCE_PRICE)) {
                        map.remove(SOURCE_PRICE);
                    }
                    //来单数量
                    if (map.containsKey(SOURCE_QUANTITY)) {
                        map.remove(SOURCE_QUANTITY);
                    }
                    groupOrderLine.setFeatures(JSON.toJSONString(map));
                }
                groupOrderLine.setRemark(null);
                groupOrderLines.add(groupOrderLine);
            });

            // F-B订单
            AtomOrderDO groupOrderDO = new AtomOrderDO();
            groupOrderDO.setOrder(groupOrder);
            groupOrderDO.setOrderLines(groupOrderLines);
            groupOrderDO.setAutoSubmit(companyOrderDO.isAutoSubmit());
            groupOrderDOS.add(groupOrderDO);
        });
        return groupOrderDOS;
    }

    private void setPrice(OrderLine groupOrderLine,Map<String, PolicyPriceQueryRequest> priceQueryRequestMap){
        String priceLineKey = groupOrderLine.getScItemOutCode() + "-" + groupOrderLine.getSaleUnit();
        PolicyPriceQueryRequest subOrderInfo = priceQueryRequestMap.get(priceLineKey);
        log.info("SalesOrderParamsConvertService#setPrice#subOrderInfo={}#groupOrderLine={}#priceQueryRequestMap={}",JSON.toJSONString(subOrderInfo),JSON.toJSONString(groupOrderLine),JSON.toJSONString(priceQueryRequestMap));
        if (Objects.isNull(subOrderInfo) || Objects.isNull(subOrderInfo.getUnitPrice()) || subOrderInfo.getUnitPrice() < 0L) {
            throw new FunctionException("OC-01-001-01-16-023", "价格格式错误");
        }

        Long unitPrice = subOrderInfo.getUnitPrice();

        //设置明细的unitPrice
        groupOrderLine.setUnitPrice(String.valueOf(unitPrice));

        Long totalAmount = unitPrice * Long.valueOf(groupOrderLine.getQuantity());

        // 常规总金额
        groupOrderLine.setShouldPayFee(String.valueOf(totalAmount));

    }

    private Map<String, PolicyPriceQueryRequest> queryGoodsDetailPrice(SalesOrderAtomCreateRequest request) {
        PolicyPriceMainRequest priceMainRequest = convertPriceMainOrder(request);

        log.info("SalesOrderParamsConvertService#queryGoodsDetailPrice priceMainRequest: {}", priceMainRequest);
        List<PolicyPriceQueryRequest> policyPriceQueryRequests = normalPriceQueryUtils.queryPolicyPrice(priceMainRequest);
        log.info("SalesOrderParamsConvertService#queryGoodsDetailPrice policyPriceQueryRequests: {}", policyPriceQueryRequests);

        return Optional.ofNullable(policyPriceQueryRequests)
                .orElse(Lists.newArrayList())
                .stream()
                .collect(Collectors.toMap(o -> o.getMaterialCode() + "-" + o.getSalesUnitCode(), p -> p, (v1, v2) -> v1));
    }

    private PolicyPriceMainRequest convertPriceMainOrder(SalesOrderAtomCreateRequest request) {
        log.info("SalesOrderParamsConvertService#convertMainOrder_request:" + JSON.toJSON(request));
        PolicyPriceMainRequest mainOrderInfo = new PolicyPriceMainRequest();
        mainOrderInfo.setFromSys(request.getFromSys());
        mainOrderInfo.setSalesOrganizationCode(request.getSalesOrganizationCode());
        mainOrderInfo.setBusinessType(request.getBusinessType());
        log.info("SalesOrderParamsConvertService#convertMainOrder_mainOrderInfo:" + JSON.toJSON(mainOrderInfo));
        mainOrderInfo.setCalculateItemList(convertPriceOrderLine(request.getOrderDetails(), request));
        return mainOrderInfo;
    }

    private List<PolicyPriceQueryRequest> convertPriceOrderLine(List<SalesOrderAtomCreateLineRequest> orderDetails, SalesOrderAtomCreateRequest request) {
        if (CollectionUtils.isEmpty(orderDetails)) {
            return Lists.newArrayList();
        }
        String priceTypeCode = PriceTypeEnum.ZMN1.getCode(); // 集团销售订单查询到岸价
        List<PolicyPriceQueryRequest> responses = Lists.newArrayList();
        for (SalesOrderAtomCreateLineRequest orderLine : orderDetails) {
            if (StringUtils.isBlank(orderLine.getProductCode())) {
                continue;
            }
            PolicyPriceQueryRequest response = PolicyPriceQueryRequest.builder()
                    .priceTypeCode(priceTypeCode)
                    .orgSalesOrganizationCode(request.getSalesOrganizationCode())
                    .channelCode(request.getBusinessChannel())
                    .scItemGroupCode(request.getProductGroupCode())
                    .customerCode(request.getCustomerCode())
                    .customerSaleAddressCode(request.getCustomerCode())
                    .customerSendAddressCode(request.getShipToPartyCode())
                    .salesUnitCode(orderLine.getSalesUnitCode())
                    .materialCode(orderLine.getProductCode())
                    .departmentCode(request.getSalesDepartmentCode())
                    .factoryCode(orderLine.getDeliveryFactoryCode())
                    .storePlace(orderLine.getStockCode())
                    .build();
            responses.add(response);
        }
        return responses;
    }

    private Map<String, String> findId(List<String> organizationCodes,String productGroupCode) {

        List<SalesBizOrgByBuQueryRequest> salesBizOrgByBuQueryRequests = Lists.newArrayList();

        // 业务单元Code、组织Code、部门Code、渠道Code
        for (String organizationCode : organizationCodes) {
            SalesBizOrgByBuQueryRequest buQueryRequest = new SalesBizOrgByBuQueryRequest();
            buQueryRequest.setOrgCode(organizationCode);
            buQueryRequest.setBusinessType(productGroupCode);
            salesBizOrgByBuQueryRequests.add(buQueryRequest);
        }

        List<SalesBizOrgQueryDTO> salesBizOrgList = salesOrgAbilityAdapter.querySalesOrgByCodeAndBU(salesBizOrgByBuQueryRequests);
        log.info("copyFB request = {} result ={}",JSON.toJSONString(organizationCodes),JSON.toJSONString(salesBizOrgList));
        if(CollectionUtils.isEmpty(salesBizOrgList)) {
            return Maps.newHashMap();
        }

        Map<String, String> resultMap = Maps.newHashMap();
        for (SalesBizOrgQueryDTO p : salesBizOrgList) {
            if(String.valueOf(SalesOrgTypeEnum.SALES_ORG.getCode()).equals(p.getOrgType())) {
                // 针对销售组织特殊处理
                resultMap.put(p.getOrgType() + "_" + p.getOrgCode(), String.valueOf(p.getId()));
            } else {
                resultMap.put(p.getOrgCode(), String.valueOf(p.getId()));
            }
        }
        return resultMap;
    }

    private List<AtomOrderDO> doConvert(List<SalesOrderAtomCreateRequest> requestList){
        List<AtomOrderDO> orderDOS = SalesOrderAtomCreateRequestToAtomOrderDOConvertor.convert(requestList);

        // 查询货品信息，进行code转id
        List<String> scItemCodes = new ArrayList<>();
        orderDOS.forEach(o -> scItemCodes.addAll(o.getOrderLines().stream().map(OrderLine::getScItemId).distinct().collect(Collectors.toList())));
        Map<String, BaseDataScItemDTO> baseDataScItemMap = queryScItemInfo(scItemCodes);

        // 业态
        Map<String, DictionaryResponse> businessTypeMap = new HashMap<>();
        List<DictionaryResponse> businessTypeList = baseDataServiceAdapter.queryDictionarys(DictionaryTypeEnum.BUSINESS_TYPE.getCode());
        if (CollectionUtils.isNotEmpty(businessTypeList)) {
            businessTypeMap = businessTypeList.stream()
                    .collect(Collectors.toMap(DictionaryResponse::getCode, Function.identity(), (k1, k2) -> k2));
        }

        // 业务单元
        Map<String, DictionaryResponse> businessUnitMap = new HashMap<>();
        List<DictionaryResponse> businessUnitList = baseDataServiceAdapter.queryDictionarys(DictionaryTypeEnum.BUSINESS_UNIT_CODE.getCode());
        if (CollectionUtils.isNotEmpty(businessUnitList)) {
            businessUnitMap = businessUnitList.stream()
                    .collect(Collectors.toMap(DictionaryResponse::getCode, Function.identity(), (x1, x2) -> x2));
        }

        // 组织Code、部门Code、渠道Code
        Map<String, SalesBizOrgQueryDTO> organizationByCodes = findSalesOrgByAtomOrderDO(orderDOS);
        Map<String, String> organizationIdByCodes = Maps.newHashMap();
        organizationByCodes.forEach((code, dto)-> organizationIdByCodes.put(code, String.valueOf(dto.getId())));

        Map<String, WarehouseInfo> cacheWarehouseMap = Maps.newHashMap();
        for (AtomOrderDO orderDO : orderDOS) {

            String orgBisUnitCodeId = businessUnitMap.get(orderDO.getOrder().getBisUnitCode()).getId();
            String salesOrgKey = SalesOrgTypeEnum.SALES_ORG.getCode() + "_" + orderDO.getOrder().getOrganizationCode();
            if (OrderCategoryEnum.GROUP.getCode().equals(orderDO.getOrder().getOrderCategoryCode())) {
                salesOrgKey = orderDO.getOrder().getOrganizationCode();
            }
            String orgOrganizationCodeId = organizationIdByCodes.get(salesOrgKey);
            String orgDepartmentCodeId = organizationIdByCodes.get(orderDO.getOrder().getDepartmentCode());
            String orgSaleChannelCodeId = organizationIdByCodes.get(orderDO.getOrder().getSaleChannelCode());

            // 主子单仓库信息转换成ID，兼容订单共享逻辑
            for (OrderLine orderLine : orderDO.getOrderLines()) {
                WarehouseInfo warehouse = queryLgWarehouseInfo2(orderLine, cacheWarehouseMap);
                // 主单 逻辑仓转换Code->ID
                orderDO.getOrder().setWareHouseCode(warehouse.getId());
                orderDO.getOrder().setWareHouseName(warehouse.getName());
                orderDO.getOrder().setWareHouseOutCode(warehouse.getCode());
                // 主单+明细的逻辑仓信息校验 仓库-工厂-库存地点 校验
//                checkOrderLineWarehouseInfo(orderDO, warehouse);

                orderLine.setShippingWarehouseCode(warehouse.getId());
                orderLine.setShippingWarehouseName(warehouse.getName());
                orderLine.setShippingWarehouseOutCode(warehouse.getCode());
                orderLine.setDeliveryFactoryCode(warehouse.getSapFactoryCode());
                orderLine.setStockCode(warehouse.getWarehouseCode());
            }

            if (orderDO.getOrder().getBusinessType() != null
                    && businessTypeMap.containsKey(orderDO.getOrder().getBusinessType().toString())) {
                orderDO.getOrder().setBusinessTypeName(businessTypeMap.get(orderDO.getOrder().getBusinessType().toString()).getName());
            }
            if (StringUtils.isNotBlank(orderDO.getOrder().getBisUnitCode())
                    && businessUnitMap.containsKey(orderDO.getOrder().getBisUnitCode())) {
                orderDO.getOrder().setBisUnitName(businessUnitMap.get(orderDO.getOrder().getBisUnitCode()).getName());
            }

            String features = orderDO.getOrder().getFeatures();
            Map<String, String> featuresMap = JSONObject.parseObject(features, new TypeReference<Map<String, String>>() {
            });
            featuresMap = Optional.ofNullable(featuresMap).orElse(Maps.newHashMap());
            featuresMap.put("logicWarehouseCode", orderDO.getOrder().getWareHouseOutCode());

            // 新增OutCode
            orderDO.getOrder().setBisUnitOutCode(orderDO.getOrder().getBisUnitCode());
            orderDO.getOrder().setOrganizationOutCode(orderDO.getOrder().getOrganizationCode());
            orderDO.getOrder().setDepartmentOutCode(orderDO.getOrder().getDepartmentCode());
            orderDO.getOrder().setSaleChannelOutCode(orderDO.getOrder().getSaleChannelCode());
            orderDO.getOrder().setChannelOutCode(orderDO.getOrder().getChannelCode());

            // 重设为内部ID，兼容订单共享平台逻辑
            orderDO.getOrder().setBisUnitCode(orgBisUnitCodeId);
            orderDO.getOrder().setOrganizationCode(orgOrganizationCodeId);
            orderDO.getOrder().setDepartmentCode(orgDepartmentCodeId);
            orderDO.getOrder().setSaleChannelCode(orgSaleChannelCodeId);

            orderDO.getOrder().setFeatures(JSONObject.toJSONString(featuresMap));

            for (OrderLine orderLine : orderDO.getOrderLines()) {
                Map<String, String> lineFeaturesMap = JSONObject.parseObject(orderLine.getFeatures(), new TypeReference<Map<String, String>>() {
                });
                lineFeaturesMap = Optional.ofNullable(lineFeaturesMap).orElse(Maps.newHashMap());
                lineFeaturesMap.put("productCode", orderLine.getScItemId());
                lineFeaturesMap.put("logicWarehouseCode", orderLine.getShippingWarehouseOutCode());
                orderLine.setFeatures(JSONObject.toJSONString(lineFeaturesMap));

                // 货品Code转id
                BaseDataScItemDTO baseDataScItemDTO = baseDataScItemMap.get(orderLine.getScItemId());
                if (Objects.isNull(baseDataScItemDTO)) {
                    throw new FunctionException("OC-01-001-01-16-012", orderLine.getScItemId());
                }
                // 将物料编码转为ID
                orderLine.setScItemId(baseDataScItemDTO.getScItemId());
            }
        }

        return orderDOS;
    }

    private Map<String, ShipToPartyByAccurateQueryDTO> queryShipToPartyByAccurate(List<SalesOrderAtomCreateRequest> salesOrderBizCreateRequests) {
        Map<String, ItemGroupAbilityDTO> scItemGroupListQueryMap = queryScItemGroupMap();

        List<com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ShipToPartyByAccurateQueryRequest> requests = Lists.newArrayList();
        for (SalesOrderAtomCreateRequest createRequest : salesOrderBizCreateRequests) {
            if (!scItemGroupListQueryMap.containsKey(createRequest.getProductGroupCode())) {
                // 产品组不存在时，不组装入参查询送达方信息，防止接口报错所有数据都无法拿到
                continue;
            }

            com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ShipToPartyByAccurateQueryRequest queryRequest = new ShipToPartyByAccurateQueryRequest();
            queryRequest.setBusinessType(createRequest.getProductGroupCode());
            //F-B的销售组织编码
            queryRequest.setSalesOrganizationCode(createRequest.getGroupSalesOrganizationCode());
            //F-B的售达方
            queryRequest.setShipToPartyCode(createRequest.getGroupShipToPartyCode());
            //F-B的送达方
            queryRequest.setSoldToPartyCode(createRequest.getGroupCustomerCode());
            queryRequest.setSalesChannelCode(SALES_ORGANIZATION_CODE);

            requests.add(queryRequest);
        }
        if (CollectionUtils.isEmpty(requests)) {
            return Maps.newHashMap();
        }
        List<ShipToPartyByAccurateQueryDTO> listResult = shipToPartyAbilityAdapter.queryShipToPartyByAccurate(requests);
        if (CollectionUtils.isEmpty(listResult)) {
            return Maps.newHashMap();
        }

        return listResult.stream().collect(Collectors.toMap(ShipToPartyByAccurateQueryDTO::getShipToPartyCode, p -> p, (v1, v2) -> v1));
    }

    private Map<String, ItemGroupAbilityDTO> queryScItemGroupMap() {
        // 查询所有货品组数据
        ItemGroupAbilityRequest listRequest = new ItemGroupAbilityRequest();
        listRequest.setLimit(999);
        List<ItemGroupAbilityDTO> listResponse = itemQueryAdapter.queryScItemGroup(listRequest);
        return listResponse.stream().collect(Collectors.toMap(ItemGroupAbilityDTO::getProductGroupCode, p -> p, (v1, v2) -> v1));
    }

    public WarehouseInfo queryLgWarehouseInfo2(OrderLine orderLine, Map<String, WarehouseInfo> cacheWarehouseMap) {
        String shippingWarehouseCode = orderLine.getShippingWarehouseCode();
        if (StringUtils.isBlank(shippingWarehouseCode)) {

            // 查看是否已经缓存 工厂+库存地点
            String key = String.format("%s_%s", orderLine.getDeliveryFactoryCode(), orderLine.getStockCode());
            WarehouseInfo warehouseInfo = cacheWarehouseMap.get(key);
            if (Objects.nonNull(warehouseInfo)) {
                return warehouseInfo;
            }
            List<com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.LogisticWarehouseQueryRequest> logisticWarehouseQueryRequests = Lists.newArrayList();
            com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.LogisticWarehouseQueryRequest queryRequest = new com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.LogisticWarehouseQueryRequest();
            queryRequest.setFactoryCode(orderLine.getDeliveryFactoryCode());
            queryRequest.setStorageLocation(orderLine.getStockCode());
            logisticWarehouseQueryRequests.add(queryRequest);
            List<LogisticWarehouseQueryDTO> listResult = cargoZoneAdapter.queryCargoZoneListByParam(logisticWarehouseQueryRequests);

            if (CollectionUtils.isEmpty(listResult)) {
                throw new FunctionException("OC-01-001-01-16-009", String.format("工厂编码:%s, 库存地点编码:%s",
                        orderLine.getDeliveryFactoryCode(),
                        orderLine.getStockCode()));
            }
            LogisticWarehouseQueryDTO queryWarehouseInfo = listResult.get(0);
            warehouseInfo = new WarehouseInfo();
            warehouseInfo.setId(queryWarehouseInfo.getId());
            warehouseInfo.setWarehouseId(queryWarehouseInfo.getWarehouseId());
            warehouseInfo.setCode(queryWarehouseInfo.getCode());
            warehouseInfo.setName(queryWarehouseInfo.getName());
            warehouseInfo.setWarehouseCode(queryWarehouseInfo.getWarehouseCode());
            warehouseInfo.setSapFactoryCode(queryWarehouseInfo.getSapFactoryCode());

            // (缓存)交货工厂编码+交货库存地点 填充
            cacheWarehouseMap.put(key, warehouseInfo);
            return warehouseInfo;
        }

        // 查看是否已经缓存 逻辑仓库
        WarehouseInfo warehouseInfo = cacheWarehouseMap.get(shippingWarehouseCode);
        if (Objects.nonNull(warehouseInfo)) {
            return warehouseInfo;
        }

        // 若 逻辑仓已传，需要通过Code转换ID处理

        LogisticWarehouseQueryRequest queryRequest = new LogisticWarehouseQueryRequest();
        queryRequest.setLogicWarehouseCode(orderLine.getShippingWarehouseCode());
        List<LogisticWarehouseQueryRequest> logisticWarehouseQueryRequests = Lists.newArrayList(queryRequest);
        List<LogisticWarehouseQueryDTO> listResult = cargoZoneAdapter.queryCargoZoneListByParam(logisticWarehouseQueryRequests);

        if (CollectionUtils.isNotEmpty(listResult)) {
            LogisticWarehouseQueryDTO queryWarehouseInfo = listResult.get(0);

            warehouseInfo = new WarehouseInfo();
            warehouseInfo.setId(queryWarehouseInfo.getId());
            warehouseInfo.setWarehouseId(queryWarehouseInfo.getWarehouseId());
            warehouseInfo.setCode(queryWarehouseInfo.getCode());
            warehouseInfo.setName(queryWarehouseInfo.getName());
            warehouseInfo.setWarehouseCode(queryWarehouseInfo.getWarehouseCode());
            warehouseInfo.setSapFactoryCode(queryWarehouseInfo.getSapFactoryCode());
            // (缓存) 逻辑仓库
            cacheWarehouseMap.put(shippingWarehouseCode, warehouseInfo);
            return warehouseInfo;
        }
        throw new FunctionException("OC-01-001-01-16-009", String.format("逻辑仓编码:%s", shippingWarehouseCode));
    }

    private Map<String, BaseDataScItemDTO> queryScItemInfo(List<String> scItemCodes) {
        if (CollectionUtils.isEmpty(scItemCodes)) {
            return Maps.newHashMap();
        }
        SearchScItemQueryRequest request = new SearchScItemQueryRequest();
        request.setPageNum(1);
        request.setPageSize(scItemCodes.size());

        Map<String, Object> searchReqDTO = Maps.newHashMap();
        searchReqDTO.put("outerIdList", scItemCodes);
        request.setSearchReqDTO(searchReqDTO);
        List<BaseDataScItemDTO> scItemDTOS = baseDataServiceAdapter.searchScItemByDBWhenDegraded(request);

        return Optional.ofNullable(scItemDTOS).orElse(Lists.newArrayList())
                .stream()
                .collect(Collectors.toMap(BaseDataScItemDTO::getOuterId, p -> p, (v1, v2) -> v1));
    }


}
